package animationIntro;

import java.awt.Image;
import java.util.ArrayList;

public class Animation {
    //still animation vs dynamic animation
    private ArrayList<SingleScene> scenes;
    private int sceneIndex;
    private long movieTime; //total time animation has been running
    private long totalTime; //total time allowed, restart animation
    
    public Animation() {
	scenes = new ArrayList<SingleScene>();
	totalTime = 0;
	start();
    }
    
    //synchronized prevents 2 instances of method from running at once
    //adds scene to array list, set time for scene
    public synchronized void addScene(Image i, long t) {
	totalTime += t;
	scenes.add(new SingleScene(i, totalTime));
    }
    
    //start animation from beginning
    public synchronized void start() {
	movieTime = 0;
	sceneIndex = 0;
    }
    
    //change scenes
    public synchronized void update(long timePassed) {
	if (scenes.size() > 1) {
	    movieTime += timePassed;
	    if (movieTime > totalTime) {
		movieTime = 0;
		sceneIndex = 0;
	    }
	    while (movieTime > getScene(sceneIndex).endTime) {
		sceneIndex++;
	    }
	}
    }
    
    //get animation's current scene (aka image)
    public synchronized Image getImage() {
	if (scenes.size() == 0) {
	    return null;
	} else {
	    return getScene(sceneIndex).pic;
	}
    }
    private SingleScene getScene(int x) {
	return scenes.get(x);
    }
    
    //private inner class
    private class SingleScene {
	Image pic;
	long endTime;
	
	public SingleScene(Image pic, long endTime) {
	    this.pic = pic;
	    this.endTime = endTime;
	}
    }
}
